package caches

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"
)

type Ticket struct {
	AccessToken
}

func (self *Ticket) FetchTicket() (interface{}, bool) {
	client := &http.Client{Timeout: time.Duration(10 * time.Second)}
	response, error := client.Get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card&access_token=" + self.GetAccessToken())
	defer response.Body.Close()
	res, error := ioutil.ReadAll(response.Body)
	if error != nil {
		return nil, true
	}
	resultJsonMap := map[string]interface{}{}
	defodeError := json.Unmarshal(res, &resultJsonMap)
	if defodeError != nil {
		return nil, true
	}
	return resultJsonMap, false
}

func (self *Ticket) GetTicket() string {
	res := self.Get("ticket")
	if res != nil && len(string(res.([]byte))) != 0 {
		return string(res.([]byte))
	}
	ticket, errors := self.FetchTicket()
	if !errors {
		newTicket := ticket.(map[string]interface{})
		self.Put("ticket", newTicket["ticket"], time.Duration(7200*time.Second))
		return newTicket["ticket"].(string)
	}
	return ""
}

func CreateTicketSession() *Ticket {
	return &Ticket{*CreateAccesstokenSession()}
}
